"""
Case Type   : 功能测试
Case Name   : 触发器函数不支持自治事务,合理报错
Create At   : 2024/7/3
Owner       : peilinqian
Description :
    step1: 创建表;
    step2: 创建包含自治事务的触发器函数;
Expect      :
    step1: 创建表; expect：创建成功
    step2: 创建包含自治事务的触发器函数;expect:合理报错
History     :
"""
import os
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class DblinkCase(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)}:初始化----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.t_name = 't_autonomous_transaction_0037'

    def test_main(self):
        step_txt = '----step1: 创建表; expect：创建成功----'
        self.log.info(step_txt)
        sql = f"drop table if exists {self.t_name};" \
              f"create table {self.t_name} (a int,b int);"
        msg = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, msg,
                      '执行失败:' + step_txt)

        step_txt = '----step2: 创建包含自治事务的触发器函数;expect:合理报错----; '
        self.log.info(step_txt)
        sql = f'''create or replace function tri_insert_func() returns trigger as
        \$\$
        declare
         pragma autonomous_transaction;
        begin
        insert into {self.t_name} values(new.id1, new.id2, new.id3);
        return new;
        end
        \$\$ language plpgsql;
        '''
        msg = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg)
        err_flag = 'ERROR:  Triggers do not support autonomous transactions'
        self.assertIn(err_flag, msg, '执行失败:' + step_txt)

    def tearDown(self):
        self.log.info('----this is tearDown----')
        step_txt = '----删除表，恢复参数; expect：成功----'
        self.log.info(step_txt)
        sql = f"drop table if exists {self.t_name};"
        msg1 = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg1)

        self.log.info(f'----{os.path.basename(__file__)}:执行完毕----')
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, msg1,
                      '执行失败:' + step_txt)
